package banner

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"google.golang.org/protobuf/types/known/emptypb"
	"net/http"
	"strconv"
	"web/goods/api"
	"web/goods/forms"
	"web/goods/global"
	"web/goods/proto"
)

// 获取轮播图列表
func GetBannerList(ctx *gin.Context) {
	rsp, err := global.GoodsSrvClient.BannerList(context.Background(), &emptypb.Empty{})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// 添加轮播图
func CreateBanner(ctx *gin.Context) {
	f := new(forms.CreateBannerForm)
	if err := ctx.ShouldBind(&f); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	rsp, err := global.GoodsSrvClient.CreateBanner(context.Background(), &proto.BannerRequest{
		Index: f.Index,
		Image: f.Imgage,
		Url:   f.Url,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// 修改轮播图
func UpdateBanner(ctx *gin.Context) {
	idStr := ctx.Param("id")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：string转int类型发生错误")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": "解析参数出错，请检查轮播图id参数",
		})
		return
	}

	raw, _ := ctx.GetRawData()
	f := new(forms.CreateBannerForm)
	json.Unmarshal(raw, &f)

	_, err = global.GoodsSrvClient.UpdateBanner(context.Background(), &proto.BannerRequest{
		Id:    int32(idInt),
		Index: f.Index,
		Image: f.Imgage,
		Url:   f.Url,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}

// 删除轮播图
func DeleteBanner(ctx *gin.Context) {
	idStr := ctx.Param("id")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：string转int类型发生错误")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": "解析参数出错，请检查轮播图id参数",
		})
		return
	}

	_, err = global.GoodsSrvClient.DeleteBanner(context.Background(), &proto.BannerRequest{
		Id: int32(idInt),
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}
